﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LuaInterface;

namespace PengLuaKit
{
    //
    // @ PLKGame: a framework core manager
    //
    public class PLKGame : MonoSingleton<PLKGame>
    {
        public List<string> mLoadMainClass;
        public int intCurrentMainClassIndex = 0;
        public bool mIsObjCallMain = false;

        protected override void InitOnAwake()
        {
            gameObject.AddComponent<TickManager>();
            gameObject.AddComponent<toLuaManager>().OnLuaPrepareWellHandler = OnStartGameHandler;

            PLKEventDispatcher.AddCSharpEventListener("SendFromLuaEvent", OnLuaEventHanddler);
        }

        private void OnLuaEventHanddler(System.Object eventData)
        {
            Debug.Log("From lua, eventData=" + eventData);
        }

        private void OnStartGameHandler()
        {
            // excute main.lua
            // excute main.lua
            string mainClassLuaPath = "Main.lua";
            if (mLoadMainClass != null && mLoadMainClass.Count > intCurrentMainClassIndex)
                mainClassLuaPath = mLoadMainClass[intCurrentMainClassIndex];

            toLuaManager.Instance.DoFile(mainClassLuaPath);

            string mainFunName = "Main";
            if (mIsObjCallMain) mainFunName = mainClassLuaPath + "." + mainFunName;
            LuaFunction main = toLuaManager.Instance.GetFunction(mainFunName);
            main.Call();
            main.Dispose();
            main = null;
            
            // send event
            Invoke("SendUnityEvent", 1.0f);
        }

        private void SendUnityEvent()
        {
            PLKEventDispatcher.DispatcherEvent("SendFromUnityEvent", "to lua");
        }


    }
}